<template>
  <div ref="chartRef" :id="id" :class="className" :style="{ 'height': height, 'width': width }">
  </div>
</template>

<script>
export default {
  name: "mEcharts"
};
</script>

<script setup>
import * as echarts from 'echarts';

const props = defineProps({
  // 图表唯一 id
  id: String,
  // 图表类名
  className: {
    type: String,
    default: 'chart'
  },
  // 图表宽度
  width: {
    type: String,
    default: '100%'
  },
  // 图表高度
  height: {
    type: String,
    default: '100%'
  },
  // 图表数据项
  options: {
    type: Object,
    default: () => ({}),
  }
})
const { id, className, height, width } = props;
const chartRef = ref();
const chart = ref()

onMounted(() => {
  setTimeout(() => {
    chart.value = markRaw(echarts.init(chartRef.value, 'myTheme'));  // 将一个对象标记为不可被转为代理。返回该对象本身。否则tooltip不显示
    initChart()
  })
})

onBeforeMount(() => {
  // 销毁图表实例
  if (chart.value) {
    chart.value.dispose();
    chart.value = undefined
  }
})

// 监听改变
watch(() => props.options, val => {
  val && initChart(val)
}, {
  deep: true
})

const initChart = (data, clearCaching = true) => {
  if (data || props.options) {
    chart.value.setOption(data || props.options, clearCaching)
  }
}

defineExpose({
  initChart
})
</script>

<style scoped>

</style>